﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using WinVerificationService.AlertsService;
using WinVerificationService.Helpers;

namespace WinVerificationService
{
    partial class Verification : ServiceBase
    {
        private Timer _timer;
        private AlertsService.GlobalAlertsServiceClient _alertsServiceClient;
        private UserSettingsService.UserSettingsServiceClient _userSettingsServiceClient;

        public Verification()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                Trace.WriteLine("Timer should start now");
                TimerCallback timerDelegate = new TimerCallback(tmrVerification_Tick);
                _timer = new Timer(timerDelegate, null, 100, 600000);//VerificationSettings.TimePeriod
                _alertsServiceClient = new WinVerificationService.AlertsService.GlobalAlertsServiceClient();
                _userSettingsServiceClient = new WinVerificationService.UserSettingsService.UserSettingsServiceClient();
                Trace.WriteLine("Timer started");
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("{0} trace: {1}", ex.Message, ex.StackTrace));
                throw;
            }

        }

        protected override void OnStop()
        {
            Trace.WriteLine("Timer should stop now");
            _timer.Dispose();
            Trace.WriteLine("Timer stoped");
        }

        public void tmrVerification_Tick(object sender)
        {
            Trace.WriteLine("Timer tick");
            try
            {
                Trace.WriteLine("Verification will be now");
                List<BaseAlert> alerts =AlertsAnalyzer.LookForAlerts("semTest", _alertsServiceClient);
                if(alerts.Count>0)
                {
                    Trace.WriteLine("Notification will be now");
                    NotificationHelper.NotifyUser("semTest",_userSettingsServiceClient,alerts);
                }

                //_serviceClient.VerifyUsers();
                //List<BaseAlert> alerts =_alertsServiceClient.GetAlerts("semTest").ToList();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("{0} trace: {1}", ex.Message, ex.StackTrace));
                throw;
            }
        }
    }
}
